/* eslint-disable */
import { createApp } from './app'

const isDev = process.env.NODE_ENV !== 'production'

export default context => {
  return new Promise((resolve, reject) => {
    const s = isDev && Date.now()
    const { app, router, store } = createApp()
    const { url } = context
    const fullPath = router.resolve(url).route.fullPath

    if (fullPath !== url) {
      reject({ url: fullPath })
    }
    // 设置路由地址
    router.push(url)

    router.onReady(() => {
      const matchedComponents = router.getMatchedComponents()
      // 没有匹配的路由信息
      if (!matchedComponents.length) {
        return reject({ code: 404 })
      }
      // 执行被匹配组件上的获取数据钩子
      Promise.all(matchedComponents.map(Component => {
        if (Component.asyncData) {
          return Component.asyncData({
            store,
            route: router.currentRoute
          })
        }
      })).then(() => {
        isDev && console.log(`data pre-fetch: ${Date.now() - s}ms`)
        // 将state暴露在渲染的上下文
        context.state = store.state
        resolve(app)
      }).catch(reject)
    }, reject)
  })
}
